/*
 * Copyright (C) 2010-2013 The SINA WEIBO Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.jasonsun.sharelib.platform;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.example.jasonsun.sharelib.AccessTokenKeeper;
import com.example.jasonsun.sharelib.ErrorInfo;
import com.example.jasonsun.sharelib.LogoutAPI;
import com.example.jasonsun.sharelib.R;
import com.example.jasonsun.sharelib.ShareInstance;
import com.example.jasonsun.sharelib.User;
import com.example.jasonsun.sharelib.UsersAPI;
import com.example.jasonsun.sharelib.config.Cache;
import com.example.jasonsun.sharelib.utils.ImageUtil;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMessage;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.utils.LogUtil;
import com.sina.weibo.sdk.utils.Utility;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;

/**
 * 该类演示了第三方应用如何通过微博客户端分享文字、图片、视频、音乐等。
 * 执行流程： 从本应用->微博->本应用
 *
 * @author SINA
 * @since 2013-10-22
 */
public class XlWeiboPlatform implements SharePlatform {
    public static final String KEY_SHARE_TYPE = "key_share_type";
    public static final int SHARE_CLIENT = 1;
    public static final int SHARE_ALL_IN_ONE = 2;

    /**
     * 微博微博分享接口实例
     */
    private IWeiboShareAPI mWeiboShareAPI = null;

    private int mShareType = SHARE_ALL_IN_ONE;
    private Activity mActivity;

    /**
     * SSO 授权认证实例
     */
    private SsoHandler mSsoHandler;
    /**
     * 授权认证所需要的信息
     */
    private AuthInfo mAuthInfo;
    /**
     * 登陆认证对应的listener
     */
    private AuthListener mLoginListener = new AuthListener();
    /**
     * 登出操作对应的listener
     */
    private LogOutRequestListener mLogoutListener = new LogOutRequestListener();

    public XlWeiboPlatform(Activity activity, IWeiboShareAPI weiboShareAPI) {
        mActivity = activity;
        mWeiboShareAPI = weiboShareAPI;
        init();
    }

    public XlWeiboPlatform(int shareType, Activity activity, IWeiboShareAPI weiboShareAPI) {
        mShareType = shareType;
        mActivity = activity;
        mWeiboShareAPI = weiboShareAPI;
//        init();
    }

    @Override
    public void share(int platform, String title, String content, String imgUrl, String webUrl) {
        if (platform != SharePlatform.XINLANG_WEIBO) {
            throw new IllegalArgumentException("platform wrong");
        }
        sendMessage(title, content, imgUrl, webUrl);
    }

    @Override
    public void login() {
        // 创建授权认证信息
        mAuthInfo = new AuthInfo(mActivity, Cache.sina_app_key, Cache.sina_redirect_url, Cache.sina_scope);
        if (null == mSsoHandler && mAuthInfo != null) {
            mSsoHandler = new SsoHandler(mActivity, mAuthInfo);
        }

        if (mSsoHandler != null) {
            mSsoHandler.authorize(mLoginListener);
        } else {
            LogUtil.e("hello", "Please setWeiboAuthInfo(...) for first");
        }
    }

    @Override
    public void logout() {
        new LogoutAPI(mActivity, Cache.sina_app_key, AccessTokenKeeper.readAccessToken(mActivity)).logout(mLogoutListener);
    }

    private void init() {
        // 创建微博分享接口实例
        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(mActivity, Cache.sina_app_key);

        // 注册第三方应用到微博客户端中，注册成功后该应用将显示在微博的应用列表中。
        // 但该附件栏集成分享权限需要合作申请，详情请查看 Demo 提示
        // NOTE：请务必提前注册，即界面初始化的时候或是应用程序初始化时，进行注册
//        mWeiboShareAPI.registerApp();
    }

    /**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。
     *
     * @see {@link #sendMultiMessage} 或者 {@link #sendSingleMessage}
     */
    private void sendMessage(String title, String desc, String imgUrl, String webUrl) {
        if (mShareType == SHARE_CLIENT) {
            if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
                int supportApi = mWeiboShareAPI.getWeiboAppSupportAPI();
                if (supportApi >= 10351 /*ApiUtils.BUILD_INT_VER_2_2*/) {
                    sendMultiMessage(title, desc, imgUrl, webUrl);
                } else {
                    sendSingleMessage(title, desc, imgUrl, webUrl);
                }
            } else {
                Toast.makeText(mActivity, R.string.weibosdk_demo_not_support_api_hint, Toast.LENGTH_SHORT).show();
            }
        } else if (mShareType == SHARE_ALL_IN_ONE) {
            sendMultiMessage(title, desc, imgUrl, webUrl);
        }
    }

    private void sendMultiMessage(final String title, final String desc, final String imgUrl, final String webUrl) {
        // 1. 初始化微博的分享消息
        final WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        // 用户可以分享其它媒体资源（网页、音乐、视频、声音中的一种）
        weiboMessage.textObject = getTextObj(desc);
        weiboMessage.imageObject = getImageObj(imgUrl);
        weiboMessage.mediaObject = getWebpageObj(title, desc, imgUrl, webUrl);
        // 2. 初始化从第三方到微博的消息请求
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;

        // 3. 发送请求消息到微博，唤起微博分享界面
        if (mShareType == SHARE_CLIENT) {
            mWeiboShareAPI.sendRequest(mActivity, request);
        } else if (mShareType == SHARE_ALL_IN_ONE) {
            AuthInfo authInfo = new AuthInfo(mActivity, Cache.sina_app_key, Cache.sina_redirect_url, Cache.sina_scope);
            Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(mActivity.getApplicationContext());
            String token = "";
            if (accessToken != null) {
                token = accessToken.getToken();
            }
            mWeiboShareAPI.sendRequest(mActivity, request, authInfo, token, new WeiboAuthListener() {
                @Override
                public void onWeiboException(WeiboException arg0) {
//                    Toast.makeText(mActivity, arg0.getMessage(), Toast.LENGTH_SHORT).show();
                    ShareInstance.getInstance().receiveMessage(false, null, -1, arg0.getMessage());
                }

                @Override
                public void onComplete(Bundle bundle) {
                    // TODO Auto-generated method stub
                    Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
                    AccessTokenKeeper.writeAccessToken(mActivity.getApplicationContext(), newToken);
//                    Toast.makeText(mActivity.getApplicationContext(), "onAuthorizeComplete token = " + newToken.getToken(), Toast.LENGTH_SHORT).show();
                    ShareInstance.getInstance().receiveMessage(true, null, 0, null);
                }

                @Override
                public void onCancel() {
//                    Toast.makeText(mActivity, "cancel", Toast.LENGTH_SHORT).show();
                    ShareInstance.getInstance().receiveMessage(false, null, -1, "cancel");
                }
            });
        }


//        getImageObjAsync(imgUrl, new IOnGetImgData() {
//            @Override
//            public void onGetImgData(ImageObject imageObject) {
//                weiboMessage.imageObject = imageObject;
//                weiboMessage.mediaObject = getWebpageObj(title, desc, imgUrl, webUrl);
//                // 2. 初始化从第三方到微博的消息请求
//                SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
//                // 用transaction唯一标识一个请求
//                request.transaction = String.valueOf(System.currentTimeMillis());
//                request.multiMessage = weiboMessage;
//
//                // 3. 发送请求消息到微博，唤起微博分享界面
//                if (mShareType == SHARE_CLIENT) {
//                    mWeiboShareAPI.sendRequest(mActivity, request);
//                } else if (mShareType == SHARE_ALL_IN_ONE) {
//                    AuthInfo authInfo = new AuthInfo(mActivity, Constants.XINLANG_APP_KEY, Constants.REDIRECT_URL, Constants.SCOPE);
//                    Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(mActivity.getApplicationContext());
//                    String token = "";
//                    if (accessToken != null) {
//                        token = accessToken.getToken();
//                    }
//                    mWeiboShareAPI.sendRequest(mActivity, request, authInfo, token, new WeiboAuthListener() {
//
//                        @Override
//                        public void onWeiboException(WeiboException arg0) {
//                        }
//
//                        @Override
//                        public void onComplete(Bundle bundle) {
//                            // TODO Auto-generated method stub
//                            Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
//                            AccessTokenKeeper.writeAccessToken(mActivity.getApplicationContext(), newToken);
//                            Toast.makeText(mActivity.getApplicationContext(), "onAuthorizeComplete token = " + newToken.getToken(), Toast.LENGTH_SHORT).show();
//                        }
//
//                        @Override
//                        public void onCancel() {
//                        }
//                    });
//                }
//            }
//        });
    }

    private void sendSingleMessage(String title, String desc, String imgUrl, String webUrl) {
        // 1. 初始化微博的分享消息
        // 用户可以分享文本、图片、网页、音乐、视频中的一种
        WeiboMessage weiboMessage = new WeiboMessage();
        weiboMessage.mediaObject = getWebpageObj(title, desc, imgUrl, webUrl);

        // 2. 初始化从第三方到微博的消息请求
        SendMessageToWeiboRequest request = new SendMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.message = weiboMessage;

        // 3. 发送请求消息到微博，唤起微博分享界面
        mWeiboShareAPI.sendRequest(mActivity, request);
    }


    /**
     * 创建文本消息对象。
     *
     * @return 文本消息对象。
     */
    private TextObject getTextObj(String text) {
        TextObject textObject = new TextObject();
        textObject.text = text;
        return textObject;
    }

    /**
     * 创建图片消息对象。
     *
     * @return 图片消息对象。
     */
    private ImageObject getImageObj(String imgPath) {
        ImageObject imageObject = new ImageObject();
//        //设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
//        Bitmap bitmap = BitmapFactory.decodeResource(mActivity.getResources(), R.drawable.ic_qq);
//        imageObject.setImageObject(bitmap);
        try {
            byte[] data = ImageUtil.getImageData(imgPath);
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            imageObject.setImageObject(bitmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imageObject;
    }

    /**
     * 创建图片消息对象。
     *
     * @return 图片消息对象。
     */
    private void getImageObjAsync(final String imgPath, final IOnGetImgData callback) {
//        //设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
//        Bitmap  bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_logo);
//        imageObject.setImageObject(bitmap);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    byte[] data = ImageUtil.getImageData(imgPath);
                    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                    final ImageObject imageObject = new ImageObject();
                    imageObject.setImageObject(bitmap);
                    if (callback != null) {
                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                callback.onGetImgData(imageObject);
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private interface IOnGetImgData {
        void onGetImgData(ImageObject imageObject);
    }


    /**
     * 创建多媒体（网页）消息对象。
     *
     * @return 多媒体（网页）消息对象。
     */
    private WebpageObject getWebpageObj(String title, String desc, String imgUrl, String webUrl) {
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = title;
        mediaObject.description = desc;

//        Bitmap bitmap = BitmapFactory.decodeResource(mActivity.getResources(), R.drawable.ic_qq);
//        // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
//        mediaObject.setThumbImage(bitmap);
        try {
            byte[] data = ImageUtil.getImageData(imgUrl);
            mediaObject.setThumbImage(BitmapFactory.decodeByteArray(data, 0, data.length));
        } catch (Exception e) {
            e.printStackTrace();
        }
        mediaObject.actionUrl = webUrl;
        mediaObject.defaultText = "Webpage 默认文案";
        return mediaObject;
    }

    /**
     * 登入按钮的监听器，接收授权结果。
     */
    private class AuthListener implements WeiboAuthListener {
        @Override
        public void onComplete(Bundle values) {
            Oauth2AccessToken accessToken = Oauth2AccessToken.parseAccessToken(values);
            if (accessToken != null && accessToken.isSessionValid()) {
                String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(
                        new java.util.Date(accessToken.getExpiresTime()));

                AccessTokenKeeper.writeAccessToken(mActivity.getApplicationContext(), accessToken);
            }

            getUsername();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(mActivity, e.getMessage(), Toast.LENGTH_SHORT).show();
            ShareInstance.getInstance().receiveMessage(false, null, -1, e.getMessage());
            mActivity.finish();
        }

        @Override
        public void onCancel() {
            Toast.makeText(mActivity, R.string.weibosdk_demo_toast_auth_canceled, Toast.LENGTH_SHORT).show();
            ShareInstance.getInstance().receiveMessage(false, null, -1, "cancel");
            mActivity.finish();
        }
    }

    /**
     * 微博 OpenAPI 回调接口。
     */
    private RequestListener mListener = new RequestListener() {
        @Override
        public void onComplete(String response) {
            if (!TextUtils.isEmpty(response)) {
                LogUtil.i("hello", response);
                // 调用 User#parse 将JSON串解析成User对象
                User user = User.parse(response);
                if (user != null) {
                    Toast.makeText(mActivity, "获取User信息成功，用户昵称：" + user.screen_name, Toast.LENGTH_LONG).show();
                    Log.d("hello", "name: " + user.id);
                    Bundle bundle = new Bundle();
                    bundle.putString(ShareInstance.KEY_OPEN_ID, user.id);
                    ShareInstance.getInstance().receiveMessage(true, bundle, 0, null);
                    mActivity.finish();
                } else {
                    Toast.makeText(mActivity, response, Toast.LENGTH_LONG).show();
                    ShareInstance.getInstance().receiveMessage(false, null, -1, "unknown");
                    mActivity.finish();
                }
            } else {
                ShareInstance.getInstance().receiveMessage(false, null, -1, "unknown");
                mActivity.finish();
            }
        }

        @Override
        public void onWeiboException(WeiboException e) {
            LogUtil.e("hello", e.getMessage());
            ErrorInfo info = ErrorInfo.parse(e.getMessage());
            Toast.makeText(mActivity, info.toString(), Toast.LENGTH_LONG).show();
            ShareInstance.getInstance().receiveMessage(false, null, -1, e.getMessage());
        }
    };

    private void getUsername() {
        // 获取当前已保存过的 Token
        Oauth2AccessToken mAccessToken = AccessTokenKeeper.readAccessToken(mActivity);
        // 获取用户信息接口
        UsersAPI mUsersAPI = new UsersAPI(mActivity, Cache.sina_app_key, mAccessToken);

        if (mAccessToken != null && mAccessToken.isSessionValid()) {
            long uid = Long.parseLong(mAccessToken.getUid());
            mUsersAPI.show(uid, mListener);
        } else {
            ShareInstance.getInstance().receiveMessage(false, null, -1, "unknown");
            mActivity.finish();
        }
    }


    /**
     * 登出按钮的监听器，接收登出处理结果。（API 请求结果的监听器）
     */
    private class LogOutRequestListener implements RequestListener {
        @Override
        public void onComplete(String response) {
            if (!TextUtils.isEmpty(response)) {
                try {
                    JSONObject obj = new JSONObject(response);
                    String value = obj.getString("result");

                    if ("true".equalsIgnoreCase(value)) {
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onWeiboException(WeiboException e) {
//            mTokenTextView.setText(R.string.weibosdk_demo_logout_failed);
        }
    }

    public SsoHandler getSsoHandler() {
        return mSsoHandler;
    }

    public IWeiboShareAPI getWeiboShareAPI() {
        return mWeiboShareAPI;
    }
}
